import React, { useEffect, useState } from 'react';
import { Table, Button, message, Space } from 'antd';
import axios from 'axios';
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

const CheckResult = () => {
  const LOCK_KEY = 'checkResultLocked';
  const [data, setData] = useState([]);        // 最终表格数据
  const [loading, setLoading] = useState(true);
  const [submitted, setSubmitted] = useState({}); // { stuid: true }
  const [locked, setLocked] = useState(false);

  /* -------------- 1. 组件载入：先读缓存 -------------- */
  useEffect(() => {
    const cache = JSON.parse(localStorage.getItem('checkResultSubmitted') || '{}');
    setSubmitted(cache);
    setLocked(localStorage.getItem(LOCK_KEY) === '1');
  }, []);

  /* -------------- 2. 拉数据 + 合并结果 -------------- */
  useEffect(() => {
    const fetch = async () => {
      try {
        const resRight = await axios.get('/api/isRight');
        const resStu = await axios.get('/api/students');

        const merged = resStu.data.map(stu => {
          const r = resRight.data.find(item => item.stuid === stu.id);
          return { ...stu, isright: r?.isright ?? 'undone' };
        });
        setData(merged);

        // 函数式更新，不依赖外部 submitted
        setSubmitted(prev => {
          const next = { ...prev };
          resRight.data.forEach(r => (next[r.stuid] = true));
          localStorage.setItem('checkResultSubmitted', JSON.stringify(next));
          return next;
        });
      } catch (e) {
        message.error('数据加载失败');
      } finally {
        setLoading(false);
      }
    };
    fetch();
  }, []); // ✅ 空依赖，无警告

  useEffect(() => {
    const onKey = (e) => {
      if (e.ctrlKey && e.key.toLowerCase() === 'e') {
        e.preventDefault();
        handleExport();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [data]);        // data 变化后热键仍拿到最新列表

  /* -------------- 3. 点击正确/错误 -------------- */
  const handleCheck = async (stuid, isright) => {
    if (locked) return;          // 已经锁定就不再请求
    try {
      await axios.post(
        '/api/checkIsRight',
        { stuid, isright },
        { headers: { 'Content-Type': 'application/json' } }
      );

      // 立即整表刷新（同之前）
      const [resRight, resStu] = await Promise.all([
        axios.get('/api/isRight'),
        axios.get('/api/students'),
      ]);
      const merged = resStu.data.map(stu => {
        const r = resRight.data.find(item => item.stuid === stu.id);
        return { ...stu, isright: r?.isright ?? 'undone' };
      });
      setData(merged);

      // 把后端结果写进 submitted
      setSubmitted(prev => {
        const next = { ...prev };
        resRight.data.forEach(r => (next[r.stuid] = true));
        localStorage.setItem('checkResultSubmitted', JSON.stringify(next));
        return next;
      });

      // ① 设置终端锁定标志  ② 本地状态锁定
      localStorage.setItem(LOCK_KEY, '1');
      setLocked(true);
      message.success('提交成功');
    } catch (e) {
      message.error('提交失败');
    }
  };


  /* -------------- 4. 列定义 -------------- */
  const columns = [
    { title: '姓名', dataIndex: 'name', key: 'name' },
    { title: '性别', dataIndex: 'gender', key: 'gender' },
    { title: '身高 (cm)', dataIndex: 'height', key: 'height' },
    { title: '体重 (kg)', dataIndex: 'weight', key: 'weight' },
    { title: '爱好', dataIndex: 'hobby', key: 'hobby' },
    {
      title: '核对结果',
      key: 'result',
      render: (_, record) => {
        const { id, isright } = record;
        // 锁定或已判定 → 只显示文字
        if (locked || isright !== 'undone') {
          if (isright === 'undone') return <span style={{ color: '#999' }}>未判定</span>;
          return <span style={{ color: isright ? '#52c41a' : '#ff4d4f' }}>
            {isright ? '正确' : '错误'}
          </span>;
        }
        // 未判定 → 给出按钮
        return (
          <Space>
            <Button size="small" type="primary" onClick={() => handleCheck(id, 1)}>正确</Button>
            <Button size="small" danger onClick={() => handleCheck(id, 0)}>错误</Button>
          </Space>
        );
      },
    },
  ];

  const handleExport = () => {
    // 1. 构造表头
    const headers = ['姓名', '性别', '身高(cm)', '体重(kg)', '爱好', '核对结果'];

    // 2. 把后端返回的编码转成人类可读文字
    const parseResult = (v) => {
      console.log(v)
      if (v === true) return '正确';
      if (v === false) return '错误';
      return '未判定';
    };

    // 爱好映射表
    const hobbyMap = {
      '聊天': 40,
      '运动': 50,
      '其他': 60,
      '阅读': 70,
      '游戏': 80,
    };

    // 3. 组装二维数组（第一行是表头）
    const body = data.map((stu) => [
      stu.name,
      stu.gender,
      stu.height,
      stu.weight,
      hobbyMap[stu.hobby],
      parseResult(stu.isright),
    ]);
    const sheetData = [headers, ...body];

    // 4. 生成工作簿
    const ws = XLSX.utils.aoa_to_sheet(sheetData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '核对结果');

    // 5. 写文件并触发下载
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
    saveAs(blob, `核对结果_${new Date().toLocaleDateString().replace(/\//g, '-')}.xlsx`);
  };

  return <Table rowKey="id" columns={columns} dataSource={data} loading={loading} pagination={{ pageSize: 70 }} />;
};

export default CheckResult;